<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-button type="primary" @click="addroleDialogVisible = true"
        >添加</el-button
      >
      <!-- 角色权限表单 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['borderbottom', 'vcenter', i1 == 0 ? 'bordertop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环，渲染二级权限 -->
                <el-row
                  :class="['vcenter', i2 === 0 ? '' : 'bordertop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showRoleEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addroleDialogVisible"
      width="50%"
      @close="addRoleDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        ref="addRoleFormRef"
        label-width="90px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addroleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addrole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="editRoleDialogClosed"
    >
      <!-- 内容区 -->
      <el-form
        :model="editRoleForm"
        :rules="editRoleFormRules"
        ref="editRoleFormRef"
        label-width="90px"
      >
        <el-form-item label="角色名称">
          <el-input v-model="editRoleForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      /* 角色权限列表 */
      roleList: [],
      /* 控制分配角色权限对话框 的显示与隐藏 */
      setRightDialogVisible: false,
      /* 所有权限的数据 */
      rightsList: [],
      /* 树形控件 */
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      /* 默认个勾选的权限的id */
      defKeys: [],
      roleId: '',
      /* 控制添加角色对话框 的显示与隐藏 */
      addroleDialogVisible: false,
      /* 添加角色的数据表单 */
      addRoleForm: {},
      /* 添加角色表单的验证规则 */
      addRoleFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '角色名长度在2~10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '角色描述在1~10个字符之间',
            trigger: 'blur'
          }
        ]
      },
      /* 编辑角色的数据表单 */
      editRoleForm: {},
      /* 控制编辑角色对话框 的显示与隐藏 */
      editRoleDialogVisible: false,
      /* 编辑角色表单的验证规则 */
      editRoleFormRules: {
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 10,
            message: '角色描述在0~10个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    /* 获取所有权限的列表 */
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.roleList = res.data
    },
    /* 根据ID删除对应的权限 */
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消操作')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) return this.$message.error('权限取消失败')
      this.$message.success('权限取消成功')
      role.children = res.data
    },
    /* 展示分配权限的对话框 */
    async showSetRightDialog(role) {
      this.roleId = role.id
      /* 获取所有权限数据 */
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      /* 获取权限数据 */
      this.rightsList = res.data
      /* 获取三级节点ID */
      this.getLeafKeys(role, this.defKeys)
      /* 显示对话框 */
      this.setRightDialogVisible = true
    },
    /* 通过递归的形式，获取角色下所有的三级权限的ID，并保存到defKeys中  */
    getLeafKeys(node, arr) {
      /* 如果当前node节点不包含childr树形，则是三级节点 */
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    /* 分配权限对话框关闭之后清空defKeys */
    setRightDialogClose() {
      this.defKeys = []
    },
    /* 分配权限 */
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('权限分配失败')
      }

      this.$message.success('权限分配成功')
      this.getRoleList()
      this.setRightDialogVisible = false
    },
    /* 取消添加角色后重置对话框 */
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    /* 添加角色 */
    addrole() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error('角色添加失败')
        this.$message.success('角色添加成功')
        this.addroleDialogVisible = false
        this.getRoleList()
      })
    },
    /* 点击按钮，修改角色信息 */
    editRoleInfo() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        /* 发送请求 */
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc
          }
        )
        if (res.meta.status !== 200) return this.$message.error('请求错误')
        this.$message.success('编辑成功')
        this.editRoleDialogVisible = false
        /* 重新获取角色列表 */
        this.getRoleList()
      })
    },
    /* 获取编辑角色对话框里的信息 */
    async showRoleEditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('信息获取失败')
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    /* 取消编辑角色后重置对话框 */
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    /* 根据角色Id删除角色 */
    async removeRoleById(id) {
      /* 确认是否删除 */
      const confirmResult = await this.$confirm(
        '此操作将删除该角色，是否继续',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消操作')
      /* 删除角色 */
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('角色删除成功')
      this.getRoleList()
    }
  },
  created() {
    this.getRoleList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bordertop {
  border-top: 1px solid #eee;
}
.borderbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
